class RegisterController < ApplicationController
  layout 'account'
  
  verify :method => :post, :only => [:create_user, :save_addition_info, :create_lough],
         :redirect_to => {:action => :new_user}

  attr_reader :title

  def index
    new_user
    render :action => 'new_user'
  end

  def new_user
    @title = 'Register a new account'
    @user = User.new
  end
  
  def create_user
    #@@title = 'Register a new account'
    @user = User.new(params[:user].symbolize_keys)
    if validate_recap(params, @user.errors) && @user.save
      flash[:notice] = 'Success.'
      session[:user_id] = @user.id
      redirect_to :action => 'user_success'
    else
      @title = 'Register a new account'
      render :action => 'new_user'
    end
  end
  
  def user_success
    unless session[:user_id] 
      redirect_to :action => 'new_user'
    end
    @title = 'Just one more step'
    @user = User.find_by_id(session[:user_id])
  end
  
  before_filter :check_login, 
                :only => [:new_lough, :create_lough, :lough_success]

  def new_lough
    @title = 'Create new lough'
    @lough = Lough.new
  end
  
  def create_lough
    @lough = Lough.new(params[:lough])
    @lough.user = @user
    
    if @lough.save
      flash[:notice] = 'Success.'
      AccountMailer.deliver_registration_confirm(@user)
      redirect_to :action => 'lough_success'
    else
      render :action => 'new_lough'
    end
  end
  
  def send_mail
    @user = User.find(:first)
    AccountMailer.deliver_registration_confirm(@user)
    return
  end
  
  # There should be a delay redirect to new user's lough.
  # But i don't know how to do yet, this function would be 
  # added later.
  def lough_success
    @title = 'Congratulations'    
    @lough = @user.lough
  end
  
  protected
  
  def check_login
    unless session[:user_id]
      redirect_to :action => 'new_user' and return
    end
    
    @user = User.find_by_id(session[:user_id])
    unless @user
      session[:user_id] = nil
      redirect_to :action => 'new_user' and return
    end
  end
    
end
